package cn.maihe.elg.operation.supports.electronicseal.anne.service.impl;

import cn.maihe.elg.operation.config.AnneSignConfig;
import cn.maihe.elg.operation.config.ElgConfig;
import cn.maihe.elg.operation.exception.SystemRuntimeException;
import cn.maihe.elg.operation.model.enums.ContractStatus;
import cn.maihe.elg.operation.service.order.AcceptOrderContractService;
import cn.maihe.elg.operation.supports.electronicseal.anne.AnneServiceName;
import cn.maihe.elg.operation.supports.electronicseal.anne.BaseAnneSignService;
import cn.maihe.elg.operation.supports.electronicseal.anne.bean.annesign.contract.ContractAutoSignRequest;
import cn.maihe.elg.operation.supports.electronicseal.anne.bean.annesign.contract.ContractAutoSignRequestBody;
import cn.maihe.elg.operation.supports.electronicseal.anne.bean.annesign.contract.ContractAutoSignResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Description 合同自动签署
 * @Author WJH
 * @Date 2021/08/13
 */
@Slf4j
@Service
public class ContractAutoSignService extends BaseAnneSignService<ContractAutoSignRequest, ContractAutoSignResponse> {

    @Resource
    private AcceptOrderContractService acceptOrderContractService;

    public ContractAutoSignService(AnneSignConfig anneSignConfig, ElgConfig elgConfig) {
        super(anneSignConfig, elgConfig);
    }

    @Override
    protected AnneServiceName serviceName() {
        return AnneServiceName.contract_auto_sign;
    }


    /**
     * 创建合同-发起合同签署-自动合同签署|手动签署
     */
    public void autoSign(Long anneSignContractId) {
        ContractAutoSignRequest request = this.buildBaseReq();
        ContractAutoSignRequestBody body = new ContractAutoSignRequestBody();
        body.setContractId(anneSignContractId);
        request.setBody(body);

        ContractAutoSignResponse response = null;
        try {
            //沟通确认，多人签署时存在 签署中等合同状态，目前军采都是自动签署，可以默认要么完成，要么失败，
            // 安全起见还是通过查询合同详情中的合同状态去处理后续逻辑
            //CREATED-已创建 SIGNING-签署中 REJECTED-已拒签 OVERDUE-已逾期  FINISHED-已完成
            // String status = response.getBody().getStatus();
            response = this.doPost(request);
            acceptOrderContractService.updateContractStatus(anneSignContractId, ContractStatus.FINISHED);
        } catch (Exception e) {
            log.error("自动签署合同失败：{}", e.getMessage(), e);
            throw SystemRuntimeException.error("自动签署合同失败", e);
        }

    }


}
